<template>
  <div class="unionPay wrapper_1200">
    <div class="header">
      <span class="home"><nuxt-link to="/">首頁</nuxt-link> > 確认訂單 ></span> 訂單号：{{ orderId }}
    </div>
    <div class="wrapper">
      <div class="title acea-row row-between-wrapper">
        <div>銀聯支付</div>
        <div class="amount">应付金額：<span class="num font-color">{{ totalPrice }}</span>元</div>
      </div>

      <!-- 加载状态 -->
      <p v-if="!allElementsReady">加載中...</p>

      <!-- 错误信息 -->
      <p v-if="errorMessage" class="error-message">{{ errorMessage }}</p>

      <div class="card-form" v-show="allElementsReady">
        <div class="form-title">請輸入銀行卡信息</div>

        <!-- 卡号输入 -->
        <div class="form-group">
          <div class="label">卡号</div>
          <div id="cardNumber" class="input-container"></div>
          <p class="error-text" v-if="inputErrorMessage.cardNumber">{{ inputErrorMessage.cardNumber }}</p>
        </div>

        <!-- 有效期和安全码 -->
        <div class="form-row acea-row row-between-wrapper">
          <div class="form-group half">
            <div class="label">有效期</div>
            <div id="expiry" class="input-container"></div>
            <p class="error-text" v-if="inputErrorMessage.expiry">{{ inputErrorMessage.expiry }}</p>
          </div>
          <div class="form-group half">
            <div class="label">安全码</div>
            <div id="cvc" class="input-container"></div>
            <p class="error-text" v-if="inputErrorMessage.cvc">{{ inputErrorMessage.cvc }}</p>
          </div>
        </div>

        <!-- 持卡人姓名 -->
        <div class="form-group">
          <div class="label">持卡人姓名</div>
          <input type="text" v-model="cardholderName" class="input-container" placeholder="請輸入持卡人姓名" />
        </div>

        <!-- 支付按钮 -->
        <div class="btn-container">
          <div class="pay-btn bg-color" :class="{ disabled: !allElementsComplete || isSubmitting || !cardholderName }"
            @click="handleConfirm">
            {{ isSubmitting ? '處理中...' : '确认支付' }}
          </div>
        </div>

        <!-- 处理中遮罩 -->
        <div v-if="isSubmitting" class="loading-overlay">
          <div class="loading-spinner"></div>
          <div class="loading-text">支付處理中...</div>
        </div>
      </div>
      <div class="selectPay" @click="Return"><span class="iconfont icon-fanhui"></span>選擇其他支付方式</div>
    </div>
  </div>
</template>

<script>
import { init, createElement } from '@airwallex/components-sdk';

export default {
  name: "unionPay",
  auth: "guest",
  data() {
    return {
      orderId: '',
      totalPrice: '',
      paymentIntentId: '',
      clientSecret: '',
      cardholderName: '',

      // 元素引用
      cardNumberElement: null,
      expiryElement: null,
      cvcElement: null,

      // 元素准备状态
      cardNumberReady: false,
      expiryReady: false,
      cvcReady: false,

      // 元素完成状态
      cardNumberComplete: false,
      expiryComplete: false,
      cvcComplete: false,

      // 错误消息
      inputErrorMessage: {
        cardNumber: '',
        expiry: '',
        cvc: ''
      },

      errorMessage: '',
      isSubmitting: false,

      timeName: null
    }
  },
  computed: {
    // 所有元素准备完成
    allElementsReady() {
      return this.cardNumberReady && this.expiryReady && this.cvcReady;
    },
    // 所有元素值完成输入
    allElementsComplete() {
      return this.cardNumberComplete && this.expiryComplete && this.cvcComplete && this.cardholderName;
    }
  },
  fetch({ store }) {
    store.commit('isHeader', true);
    store.commit('isFooter', true);
  },
  head() {
    return {
      title: "銀聯支付-" + this.$store.state.titleCon
    }
  },
  created() {
    this.orderId = this.$route.query.orderId;
    this.totalPrice = this.$route.query.totalPrice;
  },
  mounted() {
    this.initAirwallex();
  },
  beforeDestroy() {
    // 清除定时器
    if (this.timeName) {
      clearInterval(this.timeName);
    }

    // 移除事件监听器
    const cardNumberElement = document.getElementById('cardNumber');
    const expiryElement = document.getElementById('expiry');
    const cvcElement = document.getElementById('cvc');

    const domElementArray = [cardNumberElement, expiryElement, cvcElement];
    domElementArray.forEach(element => {
      if (element) {
        element.removeEventListener('onReady', this.onReady);
        element.removeEventListener('onChange', this.onChange);
        element.removeEventListener('onFocus', this.onFocus);
        element.removeEventListener('onBlur', this.onBlur);
      }
    });
  },
  methods: {
    async initAirwallex() {
      try {
        // 步骤1: 初始化 Airwallex SDK
        await init({
          enabledElements: ['payments'],
          env: 'prod', // 测试环境，生产环境为'prod'
        });

        // 步骤2: 获取支付意图
        await this.createPaymentIntent();

        // 步骤3: 创建卡片元素
        this.cardNumberElement = await createElement('cardNumber');
        this.expiryElement = await createElement('expiry');
        this.cvcElement = await createElement('cvc');

        // 步骤4: 挂载卡片元素
        this.cardNumberElement.mount('cardNumber');
        this.expiryElement.mount('expiry');
        this.cvcElement.mount('cvc');

        // 步骤5: 添加事件监听器
        const cardNumberElement = document.getElementById('cardNumber');
        const expiryElement = document.getElementById('expiry');
        const cvcElement = document.getElementById('cvc');

        const domElementArray = [cardNumberElement, expiryElement, cvcElement];
        domElementArray.forEach(element => {
          if (element) {
            element.addEventListener('onReady', this.onReady);
            element.addEventListener('onChange', this.onChange);
            element.addEventListener('onFocus', this.onFocus);
            element.addEventListener('onBlur', this.onBlur);
          }
        });
      } catch (error) {
        console.error('初始化支付失败:', error);
        this.errorMessage = '初始化支付失败: ' + (error.message || '未知错误');
      }
    },

    // 事件处理函数
    onReady(event) {
      const { type } = event.detail;
      if (type === 'cardNumber') {
        this.cardNumberReady = true;
      }
      if (type === 'expiry') {
        this.expiryReady = true;
      }
      if (type === 'cvc') {
        this.cvcReady = true;
      }
    },

    onChange(event) {
      const { type, complete } = event.detail;
      if (type === 'cardNumber') {
        this.cardNumberComplete = complete;
      }
      if (type === 'expiry') {
        this.expiryComplete = complete;
      }
      if (type === 'cvc') {
        this.cvcComplete = complete;
      }
    },

    onFocus(event) {
      const { type } = event.detail;
      // 清除对应字段的错误信息
      this.inputErrorMessage[type] = '';
    },

    onBlur(event) {
      const { type, error } = event.detail;
      if (error) {
        this.inputErrorMessage[type] = error.message || JSON.stringify(error);
      }
    },

    async createPaymentIntent() {
      try {
        const response = await this.$axios.post('/order/pay', {
          uni: this.orderId,
          paytype: 'unionpay',
          'from': 'pc'
        });

        if (response.data && response.msg === 'success') {
          const payInfo = response.data.result || response.data.payInfo;
          this.paymentIntentId = payInfo.payment_intent_id;
          this.clientSecret = payInfo.client_secret;
        } else {
          throw new Error(response.data.msg || '获取支付参数失败');
        }
      } catch (error) {
        console.error('获取支付参数失败:', error);
        throw error;
      }
    },

    async handleConfirm() {
      const that = this;
      if (!that.allElementsComplete || that.isSubmitting || !that.cardholderName) {
        return;
      }

      that.isSubmitting = true;
      that.errorMessage = '';

      try {
        if (that.cardNumberElement) {
          that.$nextTick(async () => {
            console.log(that.cardNumberElement.confirm);
            const response = await that.cardNumberElement?.confirm({
              id: that.paymentIntentId,
              client_secret: that.clientSecret,
              payment_method_options: {
                card: {
                  auto_capture: true
                }
              },
              payment_method: {
                card: {
                  name: that.cardholderName
                }
              }
            });
            // 处理成功响应
            console.log('支付成功:', response);
            that.$message.success('支付成功');
            that.$store.commit('cartNum', 0);
            that.getOrderCoupon(that.orderId);
            setTimeout(() => {
              that.$router.replace({ path: '/order_detail', query: { orderId: that.orderId } });
            }, 1000);
          });

        }
      } catch (error) {
        console.error('支付失败:', error);
        that.errorMessage = '支付失败: ' + (error.message || '未知错误');
        // 检查支付状态
        that.checkPaymentStatus();
      } finally {
        that.isSubmitting = false;
      }
    },

    checkPaymentStatus() {
      this.timeName = setInterval(() => {
        this.$axios.get('/pc/check_order_status/' + this.orderId).then(res => {
          if (res.data.status) {
            clearInterval(this.timeName);
            this.$message.success('支付成功');
            this.$store.commit('cartNum', 0);
            this.getOrderCoupon(this.orderId);
            setTimeout(() => {
              this.$router.replace({ path: '/order_detail', query: { orderId: this.orderId } });
            }, 1000);
          }
        }).catch(err => {
          clearInterval(this.timeName);
          this.errorMessage = err.message || '支付状态检查失败';
        });
      }, 2000);
    },

    getOrderCoupon(orderId) {
      this.$axios.post('/v2/order/product_coupon/' + orderId);
    },

    Return() {
      this.$router.go(-1);
    }
  }
}
</script>

<style scoped lang="scss">
@import '@/assets/css/variables.scss';

.unionPay {
  .header {
    color: #999999;
    height: 60px;
    line-height: 60px;

    .home {
      color: #282828;
    }
  }

  .wrapper {
    padding: 26px 30px;
    background-color: #fff;

    .title {
      margin-bottom: 30px;
      font-size: 20px;

      .amount {
        font-size: 14px;
        color: #969696;

        .num {
          font-size: 22px;
          font-weight: bold;
        }
      }
    }

    .error-message {
      color: $primary-color;
      text-align: center;
      font-size: 16px;
      margin: 20px 0;
    }

    .card-form {
      width: 100%;
      max-width: 500px;
      margin: 0 auto;
      position: relative;

      .form-title {
        font-size: 18px;
        color: #333;
        margin-bottom: 20px;
        text-align: center;
      }

      .form-group {
        margin-bottom: 20px;

        &.half {
          width: 48%;
        }

        .label {
          font-size: 14px;
          color: #333;
          margin-bottom: 8px;
        }

        .input-container {
          height: 50px;
          border: 1px solid #dcdcdc;
          border-radius: 4px;
          padding: 10px;
          width: 100%;
          background: #fff;

          &:focus {
            border-color: #0066b8;
          }
        }

        .error-text {
          color: $primary-color;
          font-size: 12px;
          margin-top: 5px;
        }
      }

      .form-row {
        display: flex;
        justify-content: space-between;
      }

      .btn-container {
        margin-top: 30px;

        .pay-btn {
          height: 50px;
          border-radius: 4px;
          width: 100%;
          color: #fff;
          font-size: 16px;
          display: flex;
          align-items: center;
          justify-content: center;
          cursor: pointer;

          &.disabled {
            background-color: #ccc;
            cursor: not-allowed;
          }
        }
      }

      .loading-overlay {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(255, 255, 255, 0.8);
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;

        .loading-spinner {
          width: 40px;
          height: 40px;
          border: 4px solid #f3f3f3;
          border-top: 4px solid #0066b8;
          border-radius: 50%;
          animation: spin 1s linear infinite;
        }

        .loading-text {
          margin-top: 10px;
          color: #333;
        }
      }
    }

    .selectPay {
      font-size: 16px;
      color: #236FE9;
      margin-top: 40px;
      cursor: pointer;
      text-align: center;

      .iconfont {
        margin-right: 16px;
        font-size: 15px;
      }
    }
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

/* 自定义卡片元素样式 */
#cardNumber,
#expiry,
#cvc {
  border: 1px solid #dcdcdc;
  border-radius: 4px;
  padding: 5px 10px;
  height: 50px;
  box-shadow: none;
  transition: all 0.3s;
}

#cardNumber:focus,
#expiry:focus,
#cvc:focus {
  border: 1px solid #0066b8;
  box-shadow: 0 0 0 2px rgba(0, 102, 184, 0.2);
}
</style>
